<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      python/Django-rest-framework框架/6-drf-认证权限频率 | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>python/Django-rest-framework框架/6-drf-认证权限频率</h2>



  <p class="post-date">2020-06-28</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><p>为了方便接下来的学习，我们创建一个新的子应用 opt</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python manage.py startapp opt</span><br></pre></td></tr></table></figure>



<p>因为接下来的功能中需要使用到登陆功能，所以我们使用django内置admin站点并创建一个管理员.</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">python3 manage.py makemigrations</span><br><span class="line">python3 manage.py migrate</span><br><span class="line">python3 manage.py createsuperuser</span><br></pre></td></tr></table></figure>

<p><img src="https://tva1.sinaimg.cn/large/007S8ZIlgy1ggipou4rkjj30ry059772.jpg" alt="1557276390641"></p>
<p>创建管理员以后，访问admin站点，先修改站点的语言配置</p>
<p>settings.py</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">LANGUAGE_CODE &#x3D; &#39;zh-hans&#39;  # 中文</span><br><span class="line"></span><br><span class="line">TIME_ZONE &#x3D; &#39;Asia&#x2F;Shanghai&#39; # 时区是亚洲上海</span><br><span class="line"></span><br><span class="line">USE_I18N &#x3D; True # 国际化</span><br><span class="line"></span><br><span class="line">USE_L10N &#x3D; True # 本地化</span><br><span class="line"></span><br><span class="line">USE_TZ &#x3D; True # 数据库是否使用TIME_ZONE，True表示使用上海的时区，False表示不使用，使用UTC时间，然后转成上海，会差8个小时</span><br></pre></td></tr></table></figure>

<p><img src="https://tva1.sinaimg.cn/large/007S8ZIlgy1ggipoy3fdhj30nh05rq3a.jpg" alt="1553043081445"></p>
<p>访问admin 站点效果：</p>
<p><img src="https://tva1.sinaimg.cn/large/007S8ZIlgy1ggipp0vaa8j311y0awjs4.jpg" alt="1553043054133"></p>
<h1 id="一-认证Authentication"><a href="#一-认证Authentication" class="headerlink" title="一 认证Authentication"></a>一 认证Authentication</h1><h2 id="1-1-自定义认证方案"><a href="#1-1-自定义认证方案" class="headerlink" title="1.1 自定义认证方案"></a>1.1 自定义认证方案</h2><h3 id="1-1-1-编写models"><a href="#1-1-1-编写models" class="headerlink" title="1.1.1 编写models"></a>1.1.1 编写models</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># models.py</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">User</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    username=models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">    password=models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">    user_type=models.IntegerField(choices=((<span class="number">1</span>,<span class="string">'超级用户'</span>),(<span class="number">2</span>,<span class="string">'普通用户'</span>),(<span class="number">3</span>,<span class="string">'二笔用户'</span>)))</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserToken</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    user=models.OneToOneField(to=<span class="string">'User'</span>)</span><br><span class="line">    token=models.CharField(max_length=<span class="number">64</span>)</span><br></pre></td></tr></table></figure>

<h3 id="1-1-2-新建认证类"><a href="#1-1-2-新建认证类" class="headerlink" title="1.1.2 新建认证类"></a>1.1.2 新建认证类</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> rest_framework.authentication <span class="keyword">import</span> BaseAuthentication</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TokenAuth</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">authenticate</span><span class="params">(self, request)</span>:</span></span><br><span class="line">        token = request.GET.get(<span class="string">'token'</span>)</span><br><span class="line">        token_obj = models.UserToken.objects.filter(token=token).first()</span><br><span class="line">        <span class="keyword">if</span> token_obj:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">raise</span> AuthenticationFailed(<span class="string">'认证失败'</span>)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">authenticate_header</span><span class="params">(self,request)</span>:</span></span><br><span class="line">        <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>

<h3 id="1-1-3-编写视图"><a href="#1-1-3-编写视图" class="headerlink" title="1.1.3 编写视图"></a>1.1.3 编写视图</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">get_random</span><span class="params">(name)</span>:</span></span><br><span class="line">    <span class="keyword">import</span> hashlib</span><br><span class="line">    <span class="keyword">import</span> time</span><br><span class="line">    md=hashlib.md5()</span><br><span class="line">    md.update(bytes(str(time.time()),encoding=<span class="string">'utf-8'</span>))</span><br><span class="line">    md.update(bytes(name,encoding=<span class="string">'utf-8'</span>))</span><br><span class="line">    <span class="keyword">return</span> md.hexdigest()</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Login</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">post</span><span class="params">(self,reuquest)</span>:</span></span><br><span class="line">        back_msg=&#123;<span class="string">'status'</span>:<span class="number">1001</span>,<span class="string">'msg'</span>:<span class="literal">None</span>&#125;</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            name=reuquest.data.get(<span class="string">'name'</span>)</span><br><span class="line">            pwd=reuquest.data.get(<span class="string">'pwd'</span>)</span><br><span class="line">            user=models.User.objects.filter(username=name,password=pwd).first()</span><br><span class="line">            <span class="keyword">if</span> user:</span><br><span class="line">                token=get_random(name)</span><br><span class="line">                models.UserToken.objects.update_or_create(user=user,defaults=&#123;<span class="string">'token'</span>:token&#125;)</span><br><span class="line">                back_msg[<span class="string">'status'</span>]=<span class="string">'1000'</span></span><br><span class="line">                back_msg[<span class="string">'msg'</span>]=<span class="string">'登录成功'</span></span><br><span class="line">                back_msg[<span class="string">'token'</span>]=token</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                back_msg[<span class="string">'msg'</span>] = <span class="string">'用户名或密码错误'</span></span><br><span class="line">        <span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">            back_msg[<span class="string">'msg'</span>]=str(e)</span><br><span class="line">        <span class="keyword">return</span> Response(back_msg)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Course</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    authentication_classes = [TokenAuth, ]</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self, request)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> HttpResponse(<span class="string">'get'</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">post</span><span class="params">(self, request)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> HttpResponse(<span class="string">'post'</span>)</span><br></pre></td></tr></table></figure>

<h3 id="1-1-4-全局使用"><a href="#1-1-4-全局使用" class="headerlink" title="1.1.4 全局使用"></a>1.1.4 全局使用</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">REST_FRAMEWORK=&#123;</span><br><span class="line">    <span class="string">"DEFAULT_AUTHENTICATION_CLASSES"</span>:[<span class="string">"app01.service.auth.Authentication"</span>,]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="1-1-5-局部使用"><a href="#1-1-5-局部使用" class="headerlink" title="1.1.5 局部使用"></a>1.1.5 局部使用</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#局部使用，只需要在视图类里加入：</span></span><br><span class="line">authentication_classes = [TokenAuth, ]</span><br></pre></td></tr></table></figure>



<h2 id="1-2-内置认证方案-需要配合权限使用"><a href="#1-2-内置认证方案-需要配合权限使用" class="headerlink" title="1.2 内置认证方案(需要配合权限使用)"></a>1.2 内置认证方案(需要配合权限使用)</h2><p>可以在配置文件中配置全局默认的认证方案</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">REST_FRAMEWORK = &#123;</span><br><span class="line">    <span class="string">'DEFAULT_AUTHENTICATION_CLASSES'</span>: (</span><br><span class="line">        <span class="string">'rest_framework.authentication.SessionAuthentication'</span>,  <span class="comment"># session认证</span></span><br><span class="line">        <span class="string">'rest_framework.authentication.BasicAuthentication'</span>,   <span class="comment"># 基本认证</span></span><br><span class="line">    )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>也可以在每个视图中通过设置authentication_classess属性来设置</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> rest_framework.authentication <span class="keyword">import</span> SessionAuthentication, BasicAuthentication</span><br><span class="line"><span class="keyword">from</span> rest_framework.views <span class="keyword">import</span> APIView</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExampleView</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    <span class="comment"># 类属性</span></span><br><span class="line">    authentication_classes = [SessionAuthentication, BasicAuthentication]</span><br><span class="line">    ...</span><br></pre></td></tr></table></figure>

<p>认证失败会有两种可能的返回值：</p>
<ul>
<li>401 Unauthorized 未认证</li>
<li>403 Permission Denied 权限被禁止</li>
</ul>
<h1 id="二-权限Permissions"><a href="#二-权限Permissions" class="headerlink" title="二 权限Permissions"></a>二 权限Permissions</h1><p>权限控制可以限制用户对于视图的访问和对于具体数据对象的访问。</p>
<ul>
<li>在执行视图的dispatch()方法前，会先进行视图访问权限的判断</li>
<li>在通过get_object()获取具体对象时，会进行模型对象访问权限的判断</li>
</ul>
<h2 id="2-1-自定义权限"><a href="#2-1-自定义权限" class="headerlink" title="2.1 自定义权限"></a>2.1 自定义权限</h2><h3 id="2-1-1-编写权限类"><a href="#2-1-1-编写权限类" class="headerlink" title="2.1.1 编写权限类"></a>2.1.1 编写权限类</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 限制只有超级用户能访问</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.permissions <span class="keyword">import</span> BasePermission</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserPermission</span><span class="params">(BasePermission)</span>:</span></span><br><span class="line">    message = <span class="string">'不是超级用户，查看不了'</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">has_permission</span><span class="params">(self, request, view)</span>:</span></span><br><span class="line">        <span class="comment"># user_type = request.user.get_user_type_display()</span></span><br><span class="line">        <span class="comment"># if user_type == '超级用户':</span></span><br><span class="line">        <span class="comment"># 权限在认证之后，所以能取到user</span></span><br><span class="line">        user_type = request.user.user_type</span><br><span class="line">        print(user_type)</span><br><span class="line">        <span class="keyword">if</span> user_type == <span class="number">1</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span></span><br></pre></td></tr></table></figure>

<h3 id="2-1-2-全局使用"><a href="#2-1-2-全局使用" class="headerlink" title="2.1.2 全局使用"></a>2.1.2 全局使用</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">REST_FRAMEWORK=&#123;</span><br><span class="line">    <span class="string">"DEFAULT_AUTHENTICATION_CLASSES"</span>:[<span class="string">"app01.service.auth.Authentication"</span>,],</span><br><span class="line">    <span class="string">"DEFAULT_PERMISSION_CLASSES"</span>:[<span class="string">"app01.service.permissions.SVIPPermission"</span>,]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="2-1-3-局部使用"><a href="#2-1-3-局部使用" class="headerlink" title="2.1.3 局部使用"></a>2.1.3 局部使用</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 局部使用只需要在视图类里加入：</span></span><br><span class="line">permission_classes = [UserPermission,]</span><br></pre></td></tr></table></figure>

<h3 id="2-1-4-说明"><a href="#2-1-4-说明" class="headerlink" title="2.1.4 说明"></a>2.1.4 说明</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">如需自定义权限，需继承rest_framework.permissions.BasePermission父类，并实现以下两个任何一个方法或全部</span><br><span class="line">- `.has_permission(self, request, view)`</span><br><span class="line">  是否可以访问视图， view表示当前视图对象</span><br><span class="line"></span><br><span class="line">- `.has_object_permission(self, request, view, obj)`</span><br><span class="line">  是否可以访问数据对象， view表示当前视图， obj为数据对象</span><br></pre></td></tr></table></figure>



<h2 id="2-2-内置权限"><a href="#2-2-内置权限" class="headerlink" title="2.2 内置权限"></a>2.2 内置权限</h2><h3 id="2-2-1-内置权限类"><a href="#2-2-1-内置权限类" class="headerlink" title="2.2.1 内置权限类"></a>2.2.1 内置权限类</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> rest_framework.permissions <span class="keyword">import</span> AllowAny,IsAuthenticated,IsAdminUser,IsAuthenticatedOrReadOnly</span><br><span class="line">- AllowAny 允许所有用户</span><br><span class="line">- IsAuthenticated 仅通过认证的用户</span><br><span class="line">- IsAdminUser 仅管理员用户</span><br><span class="line">- IsAuthenticatedOrReadOnly 已经登陆认证的用户可以对数据进行增删改操作，没有登陆认证的只能查看数据。</span><br></pre></td></tr></table></figure>

<h3 id="2-2-2-全局使用"><a href="#2-2-2-全局使用" class="headerlink" title="2.2.2 全局使用"></a>2.2.2 全局使用</h3><p>可以在配置文件中全局设置默认的权限管理类，如</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">REST_FRAMEWORK = &#123;</span><br><span class="line">    ....</span><br><span class="line">    </span><br><span class="line">    <span class="string">'DEFAULT_PERMISSION_CLASSES'</span>: (</span><br><span class="line">        <span class="string">'rest_framework.permissions.IsAuthenticated'</span>,</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果未指明，则采用如下默认配置</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'DEFAULT_PERMISSION_CLASSES'</span>: (</span><br><span class="line">   <span class="string">'rest_framework.permissions.AllowAny'</span>,</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<h3 id="2-2-3-局部使用"><a href="#2-2-3-局部使用" class="headerlink" title="2.2.3 局部使用"></a>2.2.3 局部使用</h3><p>也可以在具体的视图中通过permission_classes属性来设置，如</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> rest_framework.permissions <span class="keyword">import</span> IsAuthenticated</span><br><span class="line"><span class="keyword">from</span> rest_framework.views <span class="keyword">import</span> APIView</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExampleView</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    permission_classes = (IsAuthenticated,)</span><br><span class="line">    ...</span><br></pre></td></tr></table></figure>



<h3 id="2-2-4-实际操作"><a href="#2-2-4-实际操作" class="headerlink" title="2.2.4 实际操作"></a>2.2.4 实际操作</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 创建超级用户，登陆到admin，创建普通用户（注意设置职员状态，也就是能登陆）</span></span><br><span class="line"><span class="comment"># 全局配置IsAuthenticated</span></span><br><span class="line"><span class="comment"># setting.py</span></span><br><span class="line"><span class="string">'DEFAULT_PERMISSION_CLASSES'</span>: (</span><br><span class="line">        <span class="string">'rest_framework.permissions.IsAuthenticated'</span>,</span><br><span class="line">    )</span><br><span class="line"><span class="comment"># urls.py</span></span><br><span class="line"> path(<span class="string">'test/'</span>, views.TestView.as_view()),</span><br><span class="line"><span class="comment"># views.py</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TestView</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self,request)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> Response(&#123;<span class="string">'msg'</span>:<span class="string">'个人中心'</span>&#125;)</span><br><span class="line"><span class="comment"># 登陆到admin后台后，直接访问可以，如果没登陆，不能访问</span></span><br><span class="line"></span><br><span class="line"><span class="comment">##注意：如果全局配置了</span></span><br><span class="line">rest_framework.permissions.IsAdminUser</span><br><span class="line"><span class="comment"># 就只有管理员能访问，普通用户访问不了</span></span><br></pre></td></tr></table></figure>

<h1 id="三-限流Throttling"><a href="#三-限流Throttling" class="headerlink" title="三 限流Throttling"></a>三 限流Throttling</h1><p>可以对接口访问的频次进行限制，以减轻服务器压力。</p>
<p>一般用于付费购买次数,投票等场景使用.</p>
<h2 id="3-1-自定义频率类"><a href="#3-1-自定义频率类" class="headerlink" title="3.1 自定义频率类"></a>3.1 自定义频率类</h2><h3 id="3-1-1-编写频率类"><a href="#3-1-1-编写频率类" class="headerlink" title="3.1.1 编写频率类"></a>3.1.1 编写频率类</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 自定义的逻辑</span></span><br><span class="line"><span class="comment">#（1）取出访问者ip</span></span><br><span class="line"><span class="comment">#（2）判断当前ip不在访问字典里，添加进去，并且直接返回True,表示第一次访问，在字典里，继续往下走</span></span><br><span class="line"><span class="comment">#（3）循环判断当前ip的列表，有值，并且当前时间减去列表的最后一个时间大于60s，把这种数据pop掉，这样列表中只有60s以内的访问时间，</span></span><br><span class="line"><span class="comment">#（4）判断，当列表小于3，说明一分钟以内访问不足三次，把当前时间插入到列表第一个位置，返回True，顺利通过</span></span><br><span class="line"><span class="comment">#（5）当大于等于3，说明一分钟内访问超过三次，返回False验证失败</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyThrottles</span><span class="params">()</span>:</span></span><br><span class="line">    VISIT_RECORD = &#123;&#125;</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></span><br><span class="line">        self.history=<span class="literal">None</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">allow_request</span><span class="params">(self,request, view)</span>:</span></span><br><span class="line">        <span class="comment">#（1）取出访问者ip</span></span><br><span class="line">        <span class="comment"># print(request.META)</span></span><br><span class="line">        ip=request.META.get(<span class="string">'REMOTE_ADDR'</span>)</span><br><span class="line">        <span class="keyword">import</span> time</span><br><span class="line">        ctime=time.time()</span><br><span class="line">        <span class="comment"># （2）判断当前ip不在访问字典里，添加进去，并且直接返回True,表示第一次访问</span></span><br><span class="line">        <span class="keyword">if</span> ip <span class="keyword">not</span> <span class="keyword">in</span> self.VISIT_RECORD:</span><br><span class="line">            self.VISIT_RECORD[ip]=[ctime,]</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">        self.history=self.VISIT_RECORD.get(ip)</span><br><span class="line">        <span class="comment"># （3）循环判断当前ip的列表，有值，并且当前时间减去列表的最后一个时间大于60s，把这种数据pop掉，这样列表中只有60s以内的访问时间，</span></span><br><span class="line">        <span class="keyword">while</span> self.history <span class="keyword">and</span> ctime-self.history[<span class="number">-1</span>]&gt;<span class="number">60</span>:</span><br><span class="line">            self.history.pop()</span><br><span class="line">        <span class="comment"># （4）判断，当列表小于3，说明一分钟以内访问不足三次，把当前时间插入到列表第一个位置，返回True，顺利通过</span></span><br><span class="line">        <span class="comment"># （5）当大于等于3，说明一分钟内访问超过三次，返回False验证失败</span></span><br><span class="line">        <span class="keyword">if</span> len(self.history)&lt;<span class="number">3</span>:</span><br><span class="line">            self.history.insert(<span class="number">0</span>,ctime)</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">True</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">False</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">wait</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">import</span> time</span><br><span class="line">        ctime=time.time()</span><br><span class="line">        <span class="keyword">return</span> <span class="number">60</span>-(ctime-self.history[<span class="number">-1</span>])</span><br></pre></td></tr></table></figure>

<h3 id="3-1-2-全局使用"><a href="#3-1-2-全局使用" class="headerlink" title="3.1.2 全局使用"></a>3.1.2 全局使用</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">REST_FRAMEWORK = &#123;</span><br><span class="line">    <span class="string">'DEFAULT_THROTTLE_CLASSES'</span>:[<span class="string">'app01.utils.MyThrottles'</span>,],</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-1-3-局部使用"><a href="#3-1-3-局部使用" class="headerlink" title="3.1.3 局部使用"></a>3.1.3 局部使用</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#在视图类里使用</span></span><br><span class="line">throttle_classes = [MyThrottles,]</span><br></pre></td></tr></table></figure>



<h2 id="3-2-内置频率类"><a href="#3-2-内置频率类" class="headerlink" title="3.2 内置频率类"></a>3.2 内置频率类</h2><h3 id="3-2-1-根据用户ip限制"><a href="#3-2-1-根据用户ip限制" class="headerlink" title="3.2.1 根据用户ip限制"></a>3.2.1 根据用户ip限制</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#写一个类，继承自SimpleRateThrottle，（根据ip限制）</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.throttling <span class="keyword">import</span> SimpleRateThrottle</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">VisitThrottle</span><span class="params">(SimpleRateThrottle)</span>:</span></span><br><span class="line">    scope = <span class="string">'luffy'</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_cache_key</span><span class="params">(self, request, view)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> self.get_ident(request)</span><br><span class="line"><span class="comment">#在setting里配置：（一分钟访问三次）</span></span><br><span class="line">REST_FRAMEWORK = &#123;</span><br><span class="line">    <span class="string">'DEFAULT_THROTTLE_RATES'</span>:&#123;</span><br><span class="line">        <span class="string">'luffy'</span>:<span class="string">'3/m'</span>  <span class="comment"># key要跟类中的scop对应</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 可以全局使用，局部使用</span></span><br></pre></td></tr></table></figure>

<p>了解：错误信息中文显示</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Course</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    authentication_classes = [TokenAuth, ]</span><br><span class="line">    permission_classes = [UserPermission, ]</span><br><span class="line">    throttle_classes = [MyThrottles,]</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self, request)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> HttpResponse(<span class="string">'get'</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">post</span><span class="params">(self, request)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> HttpResponse(<span class="string">'post'</span>)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">throttled</span><span class="params">(self, request, wait)</span>:</span></span><br><span class="line">        <span class="keyword">from</span> rest_framework.exceptions <span class="keyword">import</span> Throttled</span><br><span class="line">        <span class="class"><span class="keyword">class</span> <span class="title">MyThrottled</span><span class="params">(Throttled)</span>:</span></span><br><span class="line">            default_detail = <span class="string">'傻逼啊'</span></span><br><span class="line">            extra_detail_singular = <span class="string">'还有 &#123;wait&#125; second.'</span></span><br><span class="line">            extra_detail_plural = <span class="string">'出了 &#123;wait&#125; seconds.'</span></span><br><span class="line">        <span class="keyword">raise</span> MyThrottled(wait)</span><br></pre></td></tr></table></figure>

<h3 id="3-2-2-限制匿名用户每分钟访问3次"><a href="#3-2-2-限制匿名用户每分钟访问3次" class="headerlink" title="3.2.2 限制匿名用户每分钟访问3次"></a>3.2.2 限制匿名用户每分钟访问3次</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">REST_FRAMEWORK = &#123;</span><br><span class="line">    <span class="string">'DEFAULT_THROTTLE_CLASSES'</span>: (</span><br><span class="line">        <span class="string">'rest_framework.throttling.AnonRateThrottle'</span>,</span><br><span class="line">    ),</span><br><span class="line">    <span class="string">'DEFAULT_THROTTLE_RATES'</span>: &#123;</span><br><span class="line">        <span class="string">'anon'</span>: <span class="string">'3/m'</span>,</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment"># 使用 `second`, `minute`, `hour` 或`day`来指明周期。</span></span><br><span class="line"><span class="comment"># 可以全局使用，局部使用</span></span><br></pre></td></tr></table></figure>

<h3 id="3-2-3-限制登陆用户每分钟访问10次"><a href="#3-2-3-限制登陆用户每分钟访问10次" class="headerlink" title="3.2.3 限制登陆用户每分钟访问10次"></a>3.2.3 限制登陆用户每分钟访问10次</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">REST_FRAMEWORK = &#123;</span><br><span class="line">    <span class="string">'DEFAULT_THROTTLE_CLASSES'</span>: (</span><br><span class="line">        <span class="string">'rest_framework.throttling.UserRateThrottle'</span></span><br><span class="line">    ),</span><br><span class="line">    <span class="string">'DEFAULT_THROTTLE_RATES'</span>: &#123;</span><br><span class="line">        <span class="string">'user'</span>: <span class="string">'10/m'</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment"># 可以全局使用，局部使用</span></span><br></pre></td></tr></table></figure>



<h3 id="3-2-4-其他"><a href="#3-2-4-其他" class="headerlink" title="3.2.4 其他"></a>3.2.4 其他</h3><p>1） AnonRateThrottle</p>
<p>限制所有匿名未认证用户，使用IP区分用户。</p>
<p>使用<code>DEFAULT_THROTTLE_RATES[&#39;anon&#39;]</code> 来设置频次</p>
<p>2）UserRateThrottle</p>
<p>限制认证用户，使用User id 来区分。</p>
<p>使用<code>DEFAULT_THROTTLE_RATES[&#39;user&#39;]</code> 来设置频次</p>
<p>3）ScopedRateThrottle</p>
<p>限制用户对于每个视图的访问频次，使用ip或user id。</p>
<p>例如：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ContactListView</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    throttle_scope = <span class="string">'contacts'</span></span><br><span class="line">    ...</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ContactDetailView</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    throttle_scope = <span class="string">'contacts'</span></span><br><span class="line">    ...</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UploadView</span><span class="params">(APIView)</span>:</span></span><br><span class="line">    throttle_scope = <span class="string">'uploads'</span></span><br><span class="line">    ...</span><br><span class="line">REST_FRAMEWORK = &#123;</span><br><span class="line">    <span class="string">'DEFAULT_THROTTLE_CLASSES'</span>: (</span><br><span class="line">        <span class="string">'rest_framework.throttling.ScopedRateThrottle'</span>,</span><br><span class="line">    ),</span><br><span class="line">    <span class="string">'DEFAULT_THROTTLE_RATES'</span>: &#123;</span><br><span class="line">        <span class="string">'contacts'</span>: <span class="string">'1000/day'</span>,</span><br><span class="line">        <span class="string">'uploads'</span>: <span class="string">'20/day'</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="实例"><a href="#实例" class="headerlink" title="实例"></a>实例</h2><p>全局配置中设置访问频率</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'DEFAULT_THROTTLE_RATES'</span>: &#123;</span><br><span class="line">    <span class="string">'anon'</span>: <span class="string">'3/minute'</span>,</span><br><span class="line">    <span class="string">'user'</span>: <span class="string">'10/minute'</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> rest_framework.authentication <span class="keyword">import</span> SessionAuthentication</span><br><span class="line"><span class="keyword">from</span> rest_framework.permissions <span class="keyword">import</span> IsAuthenticated</span><br><span class="line"><span class="keyword">from</span> rest_framework.generics <span class="keyword">import</span> RetrieveAPIView</span><br><span class="line"><span class="keyword">from</span> rest_framework.throttling <span class="keyword">import</span> UserRateThrottle</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">StudentAPIView</span><span class="params">(RetrieveAPIView)</span>:</span></span><br><span class="line">    queryset = Student.objects.all()</span><br><span class="line">    serializer_class = StudentSerializer</span><br><span class="line">    authentication_classes = [SessionAuthentication]</span><br><span class="line">    permission_classes = [IsAuthenticated]</span><br><span class="line">    throttle_classes = (UserRateThrottle,)</span><br></pre></td></tr></table></figure>


</section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/python/Django-rest-framework%E6%A1%86%E6%9E%B6/2-drf-%E5%BA%8F%E5%88%97%E5%8C%96%E7%BB%84%E4%BB%B6/">
        <span class="nav-arrow">← </span>
        
          python/Django-rest-framework框架/2-drf-序列化组件
        
      </a>
    
    
      <a class="nav-right" href="/python/Django-rest-framework%E6%A1%86%E6%9E%B6/9-drf-JWT%E8%AE%A4%E8%AF%81/">
        
          python/Django-rest-framework框架/9-drf-JWT认证
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#一-认证Authentication"><span class="toc-nav-text">一 认证Authentication</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#1-1-自定义认证方案"><span class="toc-nav-text">1.1 自定义认证方案</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-1-1-编写models"><span class="toc-nav-text">1.1.1 编写models</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-1-2-新建认证类"><span class="toc-nav-text">1.1.2 新建认证类</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-1-3-编写视图"><span class="toc-nav-text">1.1.3 编写视图</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-1-4-全局使用"><span class="toc-nav-text">1.1.4 全局使用</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-1-5-局部使用"><span class="toc-nav-text">1.1.5 局部使用</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#1-2-内置认证方案-需要配合权限使用"><span class="toc-nav-text">1.2 内置认证方案(需要配合权限使用)</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#二-权限Permissions"><span class="toc-nav-text">二 权限Permissions</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#2-1-自定义权限"><span class="toc-nav-text">2.1 自定义权限</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-1-1-编写权限类"><span class="toc-nav-text">2.1.1 编写权限类</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-1-2-全局使用"><span class="toc-nav-text">2.1.2 全局使用</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-1-3-局部使用"><span class="toc-nav-text">2.1.3 局部使用</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-1-4-说明"><span class="toc-nav-text">2.1.4 说明</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#2-2-内置权限"><span class="toc-nav-text">2.2 内置权限</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-2-1-内置权限类"><span class="toc-nav-text">2.2.1 内置权限类</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-2-2-全局使用"><span class="toc-nav-text">2.2.2 全局使用</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-2-3-局部使用"><span class="toc-nav-text">2.2.3 局部使用</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-2-4-实际操作"><span class="toc-nav-text">2.2.4 实际操作</span></a></li></ol></li></ol></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#三-限流Throttling"><span class="toc-nav-text">三 限流Throttling</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#3-1-自定义频率类"><span class="toc-nav-text">3.1 自定义频率类</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-1-1-编写频率类"><span class="toc-nav-text">3.1.1 编写频率类</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-1-2-全局使用"><span class="toc-nav-text">3.1.2 全局使用</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-1-3-局部使用"><span class="toc-nav-text">3.1.3 局部使用</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#3-2-内置频率类"><span class="toc-nav-text">3.2 内置频率类</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-2-1-根据用户ip限制"><span class="toc-nav-text">3.2.1 根据用户ip限制</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-2-2-限制匿名用户每分钟访问3次"><span class="toc-nav-text">3.2.2 限制匿名用户每分钟访问3次</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-2-3-限制登陆用户每分钟访问10次"><span class="toc-nav-text">3.2.3 限制登陆用户每分钟访问10次</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#3-2-4-其他"><span class="toc-nav-text">3.2.4 其他</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#实例"><span class="toc-nav-text">实例</span></a></li></ol></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/python/Django-rest-framework框架/6-drf-认证权限频率/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "python/Django-rest-framework框架/6-drf-认证权限频率",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>